/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.common.client.model;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;

/**
 *  
 */
public class ModuleModel extends AbstractModel
{
	protected String group;
	protected String moduleClass;
	protected String code;
	protected boolean installed;
	protected List<ConfigurationModel> configurations;
	
	public ModuleModel(JSONObject jsonObject)
	{
		configurations = new ArrayList<ConfigurationModel>();
		update(jsonObject);
	}
	
	public void update(JSONObject jsonObject)
	{
		update();
		
		group = convertToString(jsonObject, "group");
		moduleClass = convertToString(jsonObject, "class");
		code = convertToString(jsonObject, "code");
		installed = convertToBoolean(jsonObject, "installed");
		
		buildConfigurations(jsonObject);
	}

	protected void buildConfigurations(JSONObject jsonObject)
	{
		configurations.clear();

		try {
			JSONValue listValue = jsonObject.get("configurations");

			if (listValue != null)
			{
				JSONArray jsonArray;
				if ((jsonArray = listValue.isArray()) != null)
				{
					int sz = jsonArray.size();		
					for (int i = 0; i < sz; i++)
					{
						JSONValue jsonValue = jsonArray.get(i);
						JSONObject jsonAObject;
						if ((jsonAObject = jsonValue.isObject()) != null)
						{
							ConfigurationModel configurationModel = new ConfigurationModel(jsonAObject);
							configurations.add(configurationModel);
						}
					}
				}
			}
		}
		catch (Exception e) {}
	}

	public void update()
	{
		group = "";
		moduleClass = "";
		code = "";
		installed = false;
	}

	public String getGroup() {
		return group;
	}

	public String getModuleClass() {
		return moduleClass;
	}

	public String getCode() {
		return code;
	}

	public List<ConfigurationModel> getConfigurations() {
		return configurations;
	}

	public boolean isInstalled() {
		return installed;
	}
}
